package cn.org.donald.framework.util;

import cn.org.donald.framework.constant.EncodeConstant;
import cn.org.donald.framework.pojo.dto.LoginUser;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * Request Util
 * @author ： Donald
 * @since  ： 2020/10/24 12:30
 *
 */
public class RequestUtil {

    private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * Get LoginUser entity if user has logged in.
     * @param request HttpServletRequest
     * @return LoginUser
     */
    public static LoginUser getLoginUser(HttpServletRequest request){
        String authorization = getAuthorization(request);
        try {
            return (LoginUser) redisTemplate().opsForValue().get(authorization);
        }catch (Exception e){
            logger.warn(e.getMessage());
            return null;
        }
    }

    /**
     * 获取authorization Token
     * @param request
     * @return
     */
    public static String getAuthorization(HttpServletRequest request){
        return request.getHeader(EncodeConstant.AUTHORIZATION_NAME);
    }


    /**
     * Get the real ip of the request.
     * @param request HttpServletRequest
     * @return A string if it is localhost return '127.0.0.1'
     */
    public static String getRealIp(HttpServletRequest request){
        String ip = null;


        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;//本机ip地址则返回127.0.0.1

    }


    private static RedisTemplate redisTemplate(){
        return (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
    }


    /**
     * Get user id if the user has logged in
     * @param request HttpServletRequest
     * @return long
     */
    public static Long getUserId(HttpServletRequest request) {
        try {
            String userId = request.getHeader("userId");
            return Long.parseLong(userId);
        }catch (Exception e){
            logger.warn(e.getMessage());
            return null;
        }

    }

    /**
     * Get userName by authorization
     * @param authorization authorization from request's head
     * @return userName
     */
    public static String getUserNameByAuthorization(String authorization){
        Assert.notNull(authorization,"authorization is null");
        DecodedJWT decodedJWT = JwtUtil.verify(authorization);
        return decodedJWT.getClaim("userName").asString();
    }

    /**
     * Get userId by authorization
     * @param authorization authorization from request's head
     * @return userId
     */
    public static Long getUserIdByAuthorization(String authorization){
        Assert.notNull(authorization,"authorization is null");
        DecodedJWT decodedJWT = JwtUtil.verify(authorization);
        try {
            return decodedJWT.getClaim("userId").asLong();
        } catch (Exception e){
            logger.warn(e.getMessage());
            return null;
        }
    }

    /**
     * get local host address
     * @return ip
     */
    public static String getLocalHostAddress(){
        String ip = null;

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e){
            logger.error("get local host failed !");
        }
        return ip;
    }

    /**
     * get internet server address
     * @return
     */
    public static String getInternetAddress(){
        String ip = null;
        String command = "curl ip.cip.cc";
        try {

            ip = CommandUtil.executeLinuxCommand(command);
        } catch (Exception e){
            try {
                ip = CommandUtil.executeWindowsCommand(command);
            } catch (Exception e1){
                e.printStackTrace();
                e1.printStackTrace();
            }
        }
        return ip;
    }
}
